/**
 * 操作内存中用户数据的API
 */

const USERS = {};
const expireMinutes = 20

export function addUser(token, user) {
    USERS[token] = user;
}

export function removeUser(token) {
    USERS[token] = undefined;
}

// 获取已经登录的用户信息，并刷新其过期时间
export function getUser(req) {
	return new Promise((resolve, reject) => {
		let token = req.get('Authorization');
		let user = USERS[token];
		if (!user) {
			return reject({
				code: 401,
				msg: '当前请求需要用户验证！'
			})
		}
		let intervalTime = new Date().getTime() - user.time;
		if (intervalTime > expireMinutes * 60000) {
			return reject({
				code: 401,
				msg: '当前用户session已经过期，需要重新登录！'
			})
		}
		user.time = new Date().getTime();
		return resolve(user);
	})
}